package com.huaqin.customer.expansion;

import java.util.Locale;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

import com.huaqin.customer.ConditionInterface;
import com.huaqin.salestracker.SalesTrackerService;

public class ConditionStandbyTime implements ConditionInterface{
	private String mKey;
	private String mOperator;
	private long mValues;
	private AlarmManager am;
	private boolean result = false;
	private PendingIntent pendingIntent;
	
	private static final String KEY_STANDBY_TIME = "StandbyTime";
	private boolean mResult = false;
	@Override
	public void setParam(String key, String operator, String values) {
		// TODO Auto-generated method stub
		mKey = key;
		mOperator = operator;
		mValues = Integer.parseInt(values) * 60 * 1000;
	}

	@Override
	public boolean execute() {
		// TODO Auto-generated method stub
		Log.i("ConditionStandbyTime", "==> execute()");
		
		if(!mResult && am == null){
		    am = (AlarmManager)SalesTrackerService.mContext.getSystemService(Context.ALARM_SERVICE);
		}
		Log.i("ConditionStandbyTime", "am:" + am);
		sendBrocast();
		return false;
	}
	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
	    if(pendingIntent != null){
	    	Log.i("ConditionStandbyTime", "cancel pendingIntent");
	        am.cancel(pendingIntent);
	    }
	}
	
	private void sendBrocast(){
		Log.i("ConditionStandbyTime", "==> sendBrocast() mValues:" + mValues);
		pendingIntent = PendingIntent.getBroadcast(SalesTrackerService.mContext, 0, 
			new Intent(SalesTrackerService.STCMD_SEND_AREADY), PendingIntent.FLAG_UPDATE_CURRENT);
		am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + mValues, pendingIntent);
	}

	@Override
	public boolean getResult() {
		// TODO Auto-generated method stub
		long standbytime = SystemClock.elapsedRealtime();

		if(mOperator.equals(">")){
			result = (standbytime > mValues);
		}
		else if(mOperator.equals(">=")){
			result = (standbytime >= mValues);
		}
		else if(mOperator.equals("==")){
			result = (standbytime == mValues);
		}
		else if(mOperator.equals("<=")){
			result = (standbytime <= mValues);
		}
		else if(mOperator.equals("<")){
			result = (standbytime < mValues);
		}
		else{
			Log.e("ConditionStandbyTime", "Unknown Operator:[" + mOperator + "]");
		}

		return result;
	}

	@Override
	public String getKeyDescription() {
		// TODO Auto-generated method stub
		
		int totalSecond = (int)SystemClock.elapsedRealtime()/1000;
    	int hour = totalSecond / 3600;
    	int minute = (totalSecond / 60) % 60;   
    	int second = totalSecond % 60;
        String timeString = String.format(Locale.getDefault(), "%02d:%02d:%02d", hour, minute, second);

		return "Standby Time " + mOperator + " " + mValues + " Current Standby Time:" + timeString;
	}
}
